package com.example.bottom.view;

import android.annotation.SuppressLint;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.bottom.R;
import com.google.android.material.bottomnavigation.BottomNavigationItemView;
import com.google.android.material.bottomnavigation.BottomNavigationMenuView;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.bottomnavigation.LabelVisibilityMode;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

/***
 * BottomNavigationView配合ViewPager使用
 * 1.基本使用
 * 2.为底部的bar增加动画（待做）
 */
public class BottomNavigationActivity extends AppCompatActivity {

    private BottomNavigationView bottomNavigationView;
    private ViewPagerAdapter viewPagerAdapter;
    private ViewPager viewPager;
    private MenuItem menuItem;//当前的Item

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bottom_navigation);

        bottomNavigationView = findViewById(R.id.bottomNavigationView);
        bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
//        BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
        bottomNavigationView.setLabelVisibilityMode(LabelVisibilityMode.LABEL_VISIBILITY_LABELED);
        //重复选择的监听事件
        bottomNavigationView.setOnNavigationItemReselectedListener(new BottomNavigationView.OnNavigationItemReselectedListener() {
            @Override
            public void onNavigationItemReselected(@NonNull MenuItem item) {
                Log.i("zxd", "onNavigationItemReselected: " + item.getTitle());
            }
        });
        //设置颜色选择器
        int[][] state = new int[2][];
        state[0] = new int[]{android.R.attr.state_selected};
        state[1] = new int[]{};
        int[] colors = new int[]{getResources().getColor(android.R.color.holo_blue_light), Color.parseColor("#000000")};
        ColorStateList stateList = new ColorStateList(state, colors);
        bottomNavigationView.setItemIconTintList(stateList);
        bottomNavigationView.setItemTextColor(stateList);
        //设置阴影
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            bottomNavigationView.setElevation(10f);
        }
        //设置icon的大小
        //bottomNavigationView.setItemIconSize(50);
        //设置字体活动时和非活动时的大小以及其他
        bottomNavigationView.setItemTextColor(null);
        bottomNavigationView.setItemTextAppearanceActive(R.style.bottomNavigationViewTextSelected);
        bottomNavigationView.setItemTextAppearanceInactive(R.style.bottomNavigationViewTextNormal);

        viewPager = findViewById(R.id.vp);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                Log.i("zxd", "onPageSelected: " + position + "\t" + (menuItem == null));
                if (menuItem != null) {
                    menuItem.setChecked(false);
                } else {
                    bottomNavigationView.getMenu().getItem(0).setChecked(false);
                }
                menuItem = bottomNavigationView.getMenu().getItem(position);
                menuItem.setChecked(true);
                //bottomNavigationView.setSelectedItemId(menuItem.getItemId());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(viewPagerAdapter);
        List<Fragment> list = new ArrayList<>();
        list.add(TestFragment.newInstance("首页"));
        list.add(TestFragment.newInstance("体系"));
        list.add(TestFragment.newInstance("广场"));
        list.add(TestFragment.newInstance("项目"));
        list.add(TestFragment.newInstance("个人"));
        viewPagerAdapter.setList(list);
    }

    /***
     * BottomNavigationView的item选择事件
     */
    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            Log.i("zxd", "onNavigationItemSelected: " + item.getTitle());
            menuItem = item;
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    viewPager.setCurrentItem(0);
                    return true;
                case R.id.navigation_sys:
                    //https://blog.csdn.net/u013626215/article/details/85114770
                    BottomNavigationMenuView menuView2 = (BottomNavigationMenuView) bottomNavigationView.getChildAt(0);
                    // 从BottomNavigationMenuView中获得childview, BottomNavigationItemView
                    if (1 < menuView2.getChildCount()) {
                        // 获得viewIndex对应子tab
                        View view = menuView2.getChildAt(1);
                        // 从子tab中获得其中显示图片的ImageView
                        View icon = view.findViewById(R.id.icon);
                        // 获得图标的宽度
                        int iconWidth = icon.getWidth();
                        // 获得tab的宽度/2
                        int tabWidth = view.getWidth() / 2;
                        // 计算badge要距离右边的距离
                        int spaceWidth = tabWidth - iconWidth;
                        View badge1 = LayoutInflater.from(getApplicationContext()).inflate(R.layout.menu_unrend_num, menuView2, false);
                        LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
                        lp1.leftMargin = spaceWidth / 3;
                        ((BottomNavigationItemView) view).addView(badge1, lp1);
                        TextView count = badge1.findViewById(R.id.tv_msg_count);
                        count.setText("11");
                    }

                    viewPager.setCurrentItem(1);
                    return true;
                case R.id.navigation_squ:
                    viewPager.setCurrentItem(2);
                    //添加bage
                    BottomNavigationMenuView menuView = (BottomNavigationMenuView) bottomNavigationView.getChildAt(0);
                    View tab = menuView.getChildAt(3);
                    BottomNavigationItemView itemView = (BottomNavigationItemView) tab;
                    View badge = LayoutInflater.from(getApplicationContext()).inflate(R.layout.menu_unrend_num, menuView, false);

                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
                    lp.leftMargin = dp2px(40);
                    lp.bottomMargin = dp2px(28);//BottomNavigationView的高度为50dp
                    itemView.addView(badge, lp);

                    //itemView.addView(badge);
                    TextView count = badge.findViewById(R.id.tv_msg_count);
                    count.setText("1");
                    return true;
                case R.id.navigation_pro:
                    setBNV_Badge(2, 999);
                    viewPager.setCurrentItem(3);
                    return true;
                case R.id.navigation_person:
                    setBNV_Badge(4, 9);
                    viewPager.setCurrentItem(4);
                    return true;
            }
            return false;
        }
    };

    public int dp2px(final float dpValue) {
        final float scale = Resources.getSystem().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    //https://www.jianshu.com/p/d80957cdd22c
    @SuppressLint("RestrictedApi")
    private void setBNV_Badge(int position, int num) {
        if (num <= 0) {
            return;
        }
        BottomNavigationMenuView menuView = (BottomNavigationMenuView) bottomNavigationView.getChildAt(0);
        if (null == menuView) {
            return;
        }
        if (position > menuView.getChildCount() - 1) {
            return;
        }
        BottomNavigationItemView itemView = (BottomNavigationItemView) menuView.getChildAt(position);
        View badge = LayoutInflater.from(this).inflate(R.layout.menu_unrend_num, itemView, false);
        TextView numView = badge.findViewById(R.id.tv_msg_count);
        UnreadMsgUtil.show(numView, num);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
//        lp.leftMargin = menuView.getItemIconSize();
        lp.leftMargin = dp2px(35);
        lp.bottomMargin = dp2px(28);//BottomNavigationView的高度为50dp
        itemView.addView(badge, lp);
    }
}